package OperationSystem.day1208Stocket.UDP.V1;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Client {//客户端

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        try (DatagramSocket socket = new DatagramSocket()) {
            while (true) {
                //读取用户输入
                System.out.print("随便输入什么然后回车>");
                String str = scanner.nextLine();
                //发送请求
                byte[] sendBuffer = str.getBytes("UTF-8");
                DatagramPacket sendPacket = new DatagramPacket(
                        sendBuffer, 0, sendBuffer.length,
                        InetAddress.getByName("127.0.0.1"), 9939
                );
                socket.send(sendPacket);//完成发送
                //接收响应的过程
                byte[] receiveBuffer = new byte[8192];
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, 0, receiveBuffer.length);
                socket.receive(receivePacket);
                //真正接收到响应，进行字符集解码处理
                String response = new String(receiveBuffer, 0, receivePacket.getLength(),"UTF-8");
                System.out.printf("From 服务端$|%s|%n", response);
            }
        }
    }
}
